package com.share.core.jdbc.factory;

import com.share.core.type.ShardingType;
import org.apache.shardingsphere.driver.api.yaml.YamlShardingSphereDataSourceFactory;

import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author caifan
 * @created 2021/8/11
 * description:
 */
public final class YamlDataSourceFactory {
    public static DataSource newInstance(final ShardingType shardingType) throws SQLException, IOException {
        switch (shardingType) {
            case SHARDING_DATABASES:
                return YamlShardingSphereDataSourceFactory.createDataSource(getFile("/META-INF/jdbc/sharding-databases.yaml"));
            case SHARDING_TABLES:
                return YamlShardingSphereDataSourceFactory.createDataSource(getFile("/META-INF/jdbc/sharding-tables.yaml"));
            case SHARDING_DATABASES_AND_TABLES:
                return YamlShardingSphereDataSourceFactory.createDataSource(getFile("/META-INF/jdbc/sharding-databases-tables.yaml"));
            case READWRITE_SPLITTING:
                return YamlShardingSphereDataSourceFactory.createDataSource(getFile("/META-INF/jdbc/readwrite-splitting.yaml"));
            case SHARDING_READWRITE_SPLITTING:
                return YamlShardingSphereDataSourceFactory.createDataSource(getFile("/META-INF/jdbc/sharding-readwrite-splitting.yaml"));
            default:
                throw new UnsupportedOperationException(shardingType.name());
        }
    }

    private static File getFile(final String fileName) {
        return new File(YamlDataSourceFactory.class.getResource(fileName).getFile());
    }
}
